<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=10">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
    <title>Manufacturing info system in BBA</title>
    <style>
        body, div {
            padding: 0;
            margin: 0;
        }

        .chart-body {
            background: #011935;
            overflow: hidden;
        }

        .tool-bar {
            position: fixed;
            top: 0;
            left: 0;
            z-index: 10;
            width: 100%;
        }
    </style>
</head>
<body class="chart-body">
<div id="myChart"></div>
<div class="tool-bar">
    <select name="akz_name" id="akzName">
        <option value="A821GFG2" selected>A821GFG2</option>
        <option value="A821GRG2">A821GRG2</option>
        <option value="A821GBG2">A821GBG2</option>
    </select>
</div>
<script src="/static/js/libs/jquery-3.1.1.min.js"></script>
<script src="/static/js/libs/echarts.min.js"></script>
<script src="/static/js/libs/moment.js"></script>

<script type="text/javascript">
    var $bgCanvas,
        xStart = 0,
        xEnd = 100,
        yStart = 0,
        yEnd = 100;
    var drawBackground = function (force) {
        if (!$bgCanvas || force) {
            var winHt = $win.height(),
                winWt = $win.width();
            $bgCanvas = $('<canvas></canvas>');
            $bgCanvas.css({
                position: 'fixed',
                top: 0,
                left: 0,
                zIndex: 0
            });
            var canvas = $bgCanvas[0];
            $('body').prepend($bgCanvas);
            var context = canvas.getContext("2d");
            canvas.width = winWt;
            canvas.height = winHt;
            context.lineWidth = 1;
            context.strokeStyle = 'rgba(128,128,128,0.1)';
            var tx = 0,
                ty = 0,
                interval = 20;
            while(ty < winHt) {
                ty += interval;
                context.beginPath();
                context.moveTo(0, ty + 0.5);
                context.lineTo(winWt, ty + 0.5);
                context.stroke();
            }

            while(tx < winWt) {
                tx += interval;
                context.beginPath();
                context.moveTo(tx + 0.5, 0);
                context.lineTo(tx + 0.5, winHt);
                context.stroke();
            }
        }
    };

    // 基于准备好的dom，初始化echarts实例
    var myChart,
        $win,
        timeHandler;
    var chartData = [];
    var option = {
        backgroundColor: 'transparent',
        tooltip: {
            show: true,
            padding: 10,
            trigger: 'item',
            backgroundColor: '#011935',
            borderColor: '#d0e9ff',
            borderWidth: 1,
            textStyle: {
                color: '#d0e9ff',
                fontWeight: 300
            },
            formatter: function (obj) {
                var value = obj.value;
                var result = '';
                if (value) {
                    var number = parseInt(value[0]);
                    var length = chartData.length;
                    var timeInterval = null;
                    var timeString = value[2];
                    if (number < length && chartData[number] && chartData[number][2]) {
                        var timeStart = moment(chartData[number][2], "YYYY-MM-DD HH:mm:ss");
                        var timeEnd = moment(timeString, "YYYY-MM-DD HH:mm:ss");
                        var diffVal = timeEnd.diff(timeStart);
                        timeInterval = moment.duration(diffVal, 'milliseconds').seconds();
                    }
                    timeInterval = timeInterval === null ? '-' : timeInterval + (timeInterval > 1 ? ' seconds' : ' second');

                    result = 'variables : ' + value[3] + '<br/>' +
                        'number : ' + number + '<br/>' +
                        'value : ' + value[1] + '<br/>' +
                        'datetime : ' + timeString + '<br/>' +
                        'time interval : ' + timeInterval;
                }
                return result;
            }
        },
        xAxis: [
            {
                type: 'value',
                scale: true,
                min: 0,
                max: 600,
                splitNumber: 6,
                boundaryGap: false,
                axisLabel: {
                    formatter: '{value}'
                },
                axisTick: {
                    lineStyle: {
                        width: 3
                    }
                },
                axisLabel: {
                    color: '#fff',
                    fontSize: 24,
                    formatter: function(value) {
                        return parseInt(value);
                    }
                },
                axisLine: {
                    lineStyle: {
                        width: 3,
                        color: '#d0e9ff'
                    }
                },
                splitLine: {
                    show: false
                },
                axisPointer: {
                    show: true,
                    snap: true,
                    type: 'shadow',
                    label: {
                        precision: 0,
                        backgroundColor: '#011935',
                        textStyle: {
                            color: '#d0e9ff'
                        }
                    }
                }
            }
        ],
        yAxis: [
            {
                type: 'value',
                scale: true,
                axisLabel: {
                    formatter: function (v) {
                        return v.toFixed(1);
                    }
                },
                axisTick: {
                    lineStyle: {
                        width: 3
                    }
                },
                axisLabel: {
                    color: '#fff',
                    fontSize: 24
                },
                axisLine: {
                    lineStyle: {
                        width: 3,
                        color: '#d0e9ff'
                    }
                },
                splitLine: {
                    show: false
                },
                axisPointer: {
                    z: 100
                }
            }
        ],
        series: [],
        dataZoom: [
            {
                id: 'xSlider',
                type: 'slider',
                show: true,
                xAxisIndex: [0],
                start: xStart,
                end: xEnd,
                handleSize: '150%',
                textStyle: {
                    color: '#fff'
                },
                dataBackground: {
                    lineStyle: {
                        color: '#fff'
                    }
                },
                labelPrecision: 1,
                labelFormatter: function (value) {
                    return parseInt(value);
                }
            },
            {
                id: 'ySlider',
                orient: 'vertical',
                type: 'slider',
                fillerColor: 'rgba(255,255,255,0.1)',
                show: true,
                left: '93%',
                yAxisIndex: [0],
                start: yStart,
                end: yEnd,
                filterMode: 'empty',
                handleSize: '150%',
                textStyle: {
                    color: '#fff'
                },
                dataBackground: {
                    lineStyle: {
                        color: '#fff'
                    }
                }
            }
        ]
    };

    var chartConfig = {
        'A821GFG2': {
            'description': 'Front Windshield Gluing Temperature Trend Chart',
            'counters': {
                'Z017': {
                    symbol: 'circle'
                },
                'Z018': {
                    symbol: 'diamond',
                    symbolSize: [16, 8]
                }
            },
            'yAxis': {
                min: 0,
                max: 120
            }
        },

        'A821GRG2': {
            'description': 'Rear Windshield Gluing Temperature Trend Chart',
            'counters': {
                'Z017': {
                    symbol: 'circle'
                },
                'Z018': {
                    symbol: 'diamond',
                    symbolSize: [16, 8]
                }
            },
            'yAxis': {
                min: 0,
                max: 120
            }
        },

        'A821GBG2': {
            'description': 'Triangle Window Gluing Temperature Trend Chart',
            'counters': {
                'Z017': {
                    symbol: 'circle'
                },
                'Z018': {
                    symbol: 'diamond',
                    symbolSize: [16, 8]
                }
            },
            'yAxis': {
                min: 0,
                max: 120
            }
        }
    };

    function setYAxis(akzName) {
        if (chartConfig[akzName] && chartConfig[akzName]['yAxis']) {
            var yAxis = chartConfig[akzName]['yAxis'];
            $.each(yAxis, function(idx, val) {
                option['yAxis'][0][idx] = val;
            });
        }
    }

    function buildTitle(text, config) {
        var titleOpt = {
            text: chartConfig[text]['description'],
            left: 'center',
            textStyle: {
                color: '#F0F8FF',
                fontSize: 27
            },
            subtextStyle: {
                color: '#F0F8FF',
                fontSize: 18
            }
        };
        if (chartConfig[text] && chartConfig[text]['description']) {
            titleOpt['subtext'] = text;
        }
        if (config) {
            $.extend(titleOpt, config);
        }
        return titleOpt;
    }

    function buildLegend(akzName, config) {
        var legendOpt = {
            top: 10,
            right: 100,
            textStyle: {
                color: '#fff',
                fontWeight: 600,
                fontSize: 24
            },
            selectedMode: 'multiple'
        };
        if (chartConfig[akzName] && chartConfig[akzName]['counters']) {
            var dataList = [];
            $.each(chartConfig[akzName]['counters'], function (field) {

                dataList.push({
                    name: field
                });
            });
            legendOpt['data'] = dataList;
        }
        if (config) {
            $.extend(legendOpt, config);
        }
        return legendOpt;
    }

    function buildSeries(chartData, variables, config) {
        var seriesOptions = {
            type: 'scatter',
            symbol: 'circle',
            coordinateSystem: 'cartesian2d',
            animation: false,
            symbolSize: 8,
            smooth: true,
            data: chartData,
            silent: false,
            showEffectOn: 'render',
            legendHoverLink: true,
            rippleEffect: {
                brushType: 'stroke'
            },
            hoverAnimation: true,
            emphasis: {
                itemStyle: {
                    borderColor: 'white',
                    borderWidth: 1
                }
            },
            itemStyle: {
                normal: {
                    color: function (item) {
                        var color = '#ffaa00';
                        if (item && item.value) {
                            var val = item.value[1];
                            if (val >= 50 && val <= 70) {
                                color = '#25c6fc';
                            }
                        }
                        return color;
                    }
                }
            }
        };
        var ptn = new RegExp("(\\w+)\\._PLC\\.CVI\\.(\\w+)");
        var matchList = variables.match(ptn);
        if (typeof matchList == 'object' && matchList.length == 3) {
            var akzName = matchList[1];
            var counterName = matchList[2];
            if (chartConfig[akzName] && chartConfig[akzName]['counters'][counterName]) {
                $.extend(seriesOptions, chartConfig[akzName]['counters'][counterName]);
            }
            seriesOptions['name'] = counterName;
        }
        if (config) {
            $.extend(seriesOptions, config);
        }
        return seriesOptions;
    }


    $(function () {
        initChart();

        $('#akzName').on('change', function () {
            clearInterval(timeHandler);
            loopTask();
        });

        drawBackground();

        $(window).resize(function() {
            location.reload();
        });
    });

    var initChart = function () {
        $win = $(window);
        var $myChart = $('#myChart');
        var winHt = $win.height(),
            winWt = $win.width();
        var chartHt = winHt,
            chartWt = winWt;
        $myChart.width(chartWt);
        $myChart.height(chartHt);
        myChart = echarts.init($myChart[0]);
        // 指定图表的配置项和数据
        myChart.showLoading();
        myChart.setOption(option);
        loopTask();
    };

    var loopTask = function () {
        var fetchData = function () {
            var akz_name = $('#akzName').val();
            option['title'] = buildTitle(akz_name);
            option['legend'] = buildLegend(akz_name);
            option['dataZoom'][0]['start'] = xStart;
            option['dataZoom'][0]['end'] = xEnd;
            option['dataZoom'][1]['start'] = yStart;
            option['dataZoom'][1]['end'] = yEnd;
            setYAxis(akz_name);
            $.ajax({
                url: '/Tiexi/BBT/api/manufacturing_info',
                data: {
                    akz_name: akz_name
                },
                dataType: 'json',
                type: 'get'
            }).done(function (resp) {
                // 使用刚指定的配置项和数据显示图表。
                if (resp) {
                    if (typeof resp == 'object') {
                        myChart.hideLoading();
                        option['series'] = [];
                        $.each(resp, function (k, val) {
                            chartData = [];
                            $.each(val, function (idx, obj) {
                                var arr = [idx + 1, obj['value_num'], obj['time_stamp'], k];
                                chartData.push(arr);
                            });
                            var seriesVal = buildSeries(chartData, k);
                            option['series'].push(seriesVal);
                        });
                        myChart.setOption(option);
                    }
                }
            });
        };

        fetchData();
        timeHandler = setInterval(function () {
            fetchData();
        }, 30000);

        myChart.on('datazoom', function (params) {
            if (params['dataZoomId'] == 'ySlider') {
                yStart = params['start'];
                yEnd = params['end'];
            }
            else if (params['dataZoomId'] == 'xSlider') {
                xStart = params['start'];
                xEnd = params['end'];
            }
        });
    };
</script>
</body>
</html>